﻿using System;
using System.Collections.Generic;
using System.Linq;

class PerfectNumbers
{
    static void Main(string[] args)
    {
        Console.WriteLine("找出1000以内的所有完数");
        Console.WriteLine("=====================");

        int limit = 1000;
        var perfectNumbers = FindPerfectNumbers(limit);

        DisplayResults(perfectNumbers, limit);
    }

   
    static List<(int number, List<int> factors)> FindPerfectNumbers(int limit)
    {
        var results = new List<(int, List<int>)>();

        for (int number = 2; number <= limit; number++)
        {
            var factors = GetFactors(number);
            int sum = factors.Sum();

            if (sum == number)
            {
                results.Add((number, factors));
            }
        }

        return results;
    }

    
    static List<int> GetFactors(int number)
    {
        var factors = new List<int> { 1 }; 

        
        for (int i = 2; i <= Math.Sqrt(number); i++)
        {
            if (number % i == 0)
            {
                factors.Add(i);
                if (i != number / i) 
                {
                    factors.Add(number / i);
                }
            }
        }

        factors.Sort();
        return factors;
    }

   
    static void DisplayResults(List<(int number, List<int> factors)> perfectNumbers, int limit)
    {
        if (perfectNumbers.Count == 0)
        {
            Console.WriteLine($"在1-{limit}范围内没有找到完数");
            return;
        }

        Console.WriteLine($"在1-{limit}范围内找到 {perfectNumbers.Count} 个完数：");
        Console.WriteLine();

        foreach (var (number, factors) in perfectNumbers)
        {
            Console.WriteLine($"🔹 {number} = {GetFactorizationString(factors)}");
            Console.WriteLine($"   因子：{string.Join(" + ", factors)}");
            Console.WriteLine($"   验证：{factors.Sum()} = {number}");
            Console.WriteLine();
        }

     
        Console.WriteLine("统计信息：");
        Console.WriteLine($"总共检查了 {limit} 个数");
        Console.WriteLine($"找到完数：{string.Join(", ", perfectNumbers.Select(p => p.number))}");
    }


    static string GetFactorizationString(List<int> factors)
    {
        return string.Join(" + ", factors);
    }
}